package messages.persondispatcher;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import state.Globals;
import state.person.PersonDispatcherState;
import messages.BaseMessage;
import messages.MessageType;

public class CurrentPeopleStateMessage extends BaseMessage {

    private byte[] data;
    private PersonDispatcherState deserializedState = null;
    
    public CurrentPeopleStateMessage(byte[] data)
    {
        super(data);
        
        this.data = data;
    }
    
    public CurrentPeopleStateMessage(PersonDispatcherState state) throws IOException
    {
        super(null);
        
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
        byteOutput.write(getMessageType().getIdentifier());
        
        ObjectOutputStream output = new ObjectOutputStream(byteOutput);
        
        output.writeObject(state);
        
        data = byteOutput.toByteArray();
    }

    @Override
    public byte[] toByteArray()
    {
        return data;
    }

    @Override
    public MessageType getMessageType()
    {
        return MessageType.CurrentPeopleStateMessage;
    }
    
    public PersonDispatcherState getPersonDispatcherState() throws IOException
    {
        if (deserializedState != null)
        {
            return deserializedState;
        }
        
        ByteArrayInputStream byteInput = new ByteArrayInputStream(data);
        //get rid of the identifier
        byteInput.read();
        
        ObjectInputStream objectStream = new ObjectInputStream(byteInput);
        Object result;
        try
        {
            result = objectStream.readObject();
        }
        catch (ClassNotFoundException e)
        {
            Globals.getLogger().error("Could not identify class by serializing!", e);
            return null;
        }
        
        if (result instanceof PersonDispatcherState)
        {
            deserializedState = (PersonDispatcherState) result;
            return deserializedState;
        }
        
        return null;
    }

    @Override
    public int getMessageSize()
    {
        return -1;
    }

}
